package cn.highedu.coolsharkhub.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie使用注意事项：
 * 1.Cookie写入客户端的一个文本文件 不能存入密码等要求安全性的数据
 * 2.单个Cookie的大小上限是4KB
 * 3.一个站点最多只能往客户端写20个Cookie
 */
@RestController
public class CookiesController {
    Logger logger = LoggerFactory.getLogger(CookiesController.class);

    /**
     * 往客户端(浏览器)发送Cookie
     */
    @GetMapping("/setCookies")
    public String setCookies(HttpServletResponse response) {
        logger.info("发送Cookie");
        // 创建Cookie
        Cookie cookie1 = new Cookie("name", "Tom"); // 创建一个Cookie key=name value=Tom
        Cookie cookie2 = new Cookie("age", "20");
        // 设置Cookie的有效期: Cookie创建以后是一个临时Cookie 浏览器关闭后就失效了
        cookie1.setMaxAge(20); // 单位秒
        cookie2.setMaxAge(7 * 24 * 60 * 60);
        // 通过响应写入Cookie
        response.addCookie(cookie1);
        response.addCookie(cookie2);
        return "发送Cookie";
    }
    /*@GetMapping("/getCookies")
    public String getCookies(HttpServletRequest request) {
        logger.info("读取Cookie");
        // 读取往客户端写入的所有Cookie
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            logger.info("key:{}", cookie.getName()); // 读取Cookie的key
            logger.info("value:{}", cookie.getValue()); // 读取Cookie的value
        }
        return "读取Cookie";
    }*/

    @GetMapping("/getCookies")
    public String getCookies(@CookieValue String name, @CookieValue String age) {
        logger.info("读取Cookie");
        logger.info("name:{}", name);
        logger.info("age:{}", age);
        return "读取Cookie";
    }
}
